// 生成包含100个随机数的数组
function generateRandomArray(size) {
  const arr = [];
  for (let i = 0; i < size; i++) {
    arr.push(Math.floor(Math.random() * 1000));
  }
  return arr;
}

// 插入排序算法实现
function insertionSort(arr) {
  for (let i = 1; i < arr.length; i++) {
    let current = arr[i];
    let j = i - 1;
    while (j >= 0 && arr[j] > current) {
      arr[j + 1] = arr[j];
      j--;
    }
    arr[j + 1] = current;
  }
  return arr;
}

// 将数组写入文件
function writeArrayToFile(arr, filename) {
  const fs = require('fs');
  const data = arr.join(', ');
  fs.writeFileSync(filename, data);
}

// 主程序
const randomArray = generateRandomArray(100);
console.log('原始数组:', randomArray);

const sortedArray = insertionSort(randomArray);
console.log('排序后数组:', sortedArray);

writeArrayToFile(sortedArray, 'sorted_array.txt');
console.log('排序结果已写入 sorted_array.txt');
